﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using CodePlex.Resourceful.Amazon.S3;

namespace CodePlex.Resourceful.Microsoft.Azure
{
    public class BaseAzureConnection<TClient>
        where TClient : BaseAzureClient
    {

        private readonly TClient _client;
        private readonly Tracer _tracer = new Tracer();

        protected BaseAzureConnection(TClient client)
        {
            _client = client;
        }



        public TClient Client
        {
            get
            {
                return _client;
            }
        }

        public Tracer Tracer
        {
            get
            {
                return _client.Tracer;
            }
        }






        protected NameValuePairs GetMetadata(ClientResponse response, bool includeSystem)
        {
            NameValuePairs rt = new NameValuePairs();
            foreach (string key in response.Headers.Keys)
            {

                if (key.StartsWith(AzureConstants.Headers.MicrosoftMetaPrefix))
                {
                    string userKey = key.Substring(AzureConstants.Headers.MicrosoftMetaPrefix.Length);
                    rt[userKey] = response.Headers[key];
                }
                else if (includeSystem)
                {
                    rt[key] = response.Headers[key];
                }
            }
            return rt;
        }

        protected void Assert(ClientResponse response, HttpStatus expectedStatus)
        {
            HttpStatus status = response.HttpStatus;

            if (status.Equals(expectedStatus))
            {
                return;
            }

            string responseString = response.AsString();

            string message = null;
            string code = null;
            NameValuePairs fields = null;
            try
            {
                XmlReader reader = new XmlTextReader(new StringReader(responseString));



                fields = new NameValuePairs();

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name != "Error")
                    {
                        fields[reader.Name] = Utils.ReadString(reader);
                    }
                }

                message = Utils.SafeGet(fields, "Message");
                code = Utils.SafeGet(fields, "Code");


            }
            catch (Exception ex)
            {
                throw CodePlexException.Format(ex,"An unexpected http status was received, and could not parse the output: \r\n+" + responseString);
            }
            throw S3Exception.Format(fields, "[{0}] {1}", code, message);
        }

    }
}
